<?php


namespace app\index\controller;

use app\common\Base;
use app\index\model\Business;
use app\index\model\Carts;
use app\index\model\Commodity;
use app\index\model\CommodityAppraises;
use app\index\model\CommodityClass;
use app\index\model\Favorites;
use app\index\model\History;
use app\index\model\Order;
use app\index\model\OrderCommodity;
use app\index\model\User;
use think\Exception;
use think\Request;

/**
 * Class MerchantsPage 商家页
 * @package app\index\controller
 */
class MerchantsPage extends Base
{
    /**
     * @qualityComment  商家页评论-按质量排序
     * @param Request $request
     * @param CommodityAppraises $commodityAppraises
     * @param User $user
     * @param Business $business
     * @return \think\response\Json
     */
    public function qualityComment(Request $request,CommodityAppraises $commodityAppraises,User $user,Business $business){
        try {
            $businessId = $request->post('businessId');
            $commentData = $commodityAppraises->qualityComment($businessId);
            if ($commentData->isEmpty()){
                return responseJson(Base::OK,'暂无评论');
            }
            $commentData = $this->assoc_unique($commentData,'orderId');
            foreach ($commentData as $key => $val){
                $commentData[$key]['Evaluation'] = $commentData[$key]['commodityScore'] + $commentData[$key]['serviceScore'] + $commentData[$key]['timeScore'];
                unset($commentData[$key]['commodityScore'],$commentData[$key]['serviceScore'],$commentData[$key]['timeScore']);
                if (empty($userData = $user->commentUsernameHeader($commentData[$key]['userId']))) {
                    return responseJson(Base::FAIL,'数据获取失败，请重试');
                }
                $commentData[$key]['username'] = $userData['username'];
                $commentData[$key]['header'] = $userData['header'];
                $commentData[$key]['createTime'] = self::commentTime($commentData[$key]['createTime']);
                if (!$commentData[$key]['businessName'] = $business->findBusiness($commentData[$key]['businessId'])) {
                    return responseJson(Base::FAIL,'数据获取失败，请重试');
                }
                $commentData[$key]['replyTime'] = self::commentTime($commentData[$key]['replyTime']);
            }

            for ($i=0;$i<count($commentData);$i++){
                for ($j=$i;$j<count($commentData)-1;$j++){
                    if ($commentData[$i]['Evaluation'] < $commentData[$j+1]['Evaluation']){
                        $str = $commentData[$i]['Evaluation'];
                        $commentData[$i]['Evaluation'] = $commentData[$j+1]['Evaluation'];
                        $commentData[$j+1]['Evaluation'] = $str;
                    }
                }
            }
            return responseJson(Base::OK,'数据获取成功',$commentData);
        }catch (Exception $e){
            throw $e;
        }
    }
    /**
     * @comment 商家页评论-按时间排序
     * @param Request $request
     * @param CommodityAppraises $commodityAppraises
     * @param User $user
     * @param Business $business
     * @return \think\response\Json
     * @throws Exception
     */
    public function comment(Request $request,CommodityAppraises $commodityAppraises,User $user,Business $business){
        try {
            $businessId = $request->post('businessId');
            $commentData = $commodityAppraises->businessComment($businessId);
            if ($commentData->isEmpty()){
                return responseJson(Base::OK,'暂无评论');
            }
            $commentData = $this->assoc_unique($commentData,'orderId');
            foreach ($commentData as $key => $val){
                if (empty($userData = $user->commentUsernameHeader($commentData[$key]['userId']))) {
                    return responseJson(Base::FAIL,'数据获取失败，请重试');
                }
                $commentData[$key]['username'] = $userData['username'];
                $commentData[$key]['header'] = $userData['header'];
                $commentData[$key]['createTime'] = self::commentTime($commentData[$key]['createTime']);
                if (!$commentData[$key]['businessName'] = $business->findBusiness($commentData[$key]['businessId'])) {
                    return responseJson(Base::FAIL,'数据获取失败，请重试');
                }
                $commentData[$key]['replyTime'] = self::commentTime($commentData[$key]['replyTime']);
            }
            return responseJson(Base::OK,'数据获取成功',$commentData);
        }catch (Exception $e){
            throw $e;
        }
    }



    /**
     * @businessInfo    商家页信息
     * @param Request $request
     * @param Business $business
     * @param CommodityAppraises $commodityAppraises
     * @return \think\response\Json
     * @throws Exception
     */
    public function businessInfo(Request $request,Business $business,CommodityAppraises $commodityAppraises){
        try {
            $businessId = (int)$request->post('id');
            if (empty($data = $business->BusinessInfo($businessId))) {
                return responseJson(Base::FAIL,'数据获取失败');
            }

            //五星评价
            $data['Evaluation'] = ceil(($commodityAppraises->commodityScore($businessId) + $commodityAppraises->serviceScore($businessId) + $commodityAppraises->timeScore($businessId))/3);

            $address = $data['provide'].$data['city'].$data['county'].$data['street'].$data['businessAddress'];
            $data['address'] = $address;
            unset($data['provide'],$data['city'],$data['county'],$data['street'],$data['businessAddress']);
            return responseJson(Base::OK,'数据获取成功',$data);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @youLike 商家页-猜你喜欢
     * @param Business $business
     * @param Order $order
     * @return \think\response\Json
     * @throws Exception
     */
    public function youLike(Business $business,Order $order){
        try {
            if (!$data = json_decode($business->randBusiness('id,businessName,businessImg,startDeliver'),true)) {
                return responseJson(Base::FAIL,'数据获取失败,请重试');
            }
            if (empty($data)){
                return responseJson(Base::FAIL,'暂无数据');
            }
            if (count($data) < 6){
                $businessData = $data;
            }else{
                $arr = array_rand($data,6);
                shuffle($arr);
                $businessData = [];
                foreach ($arr as $value){
                    array_push($businessData,$data[$value]);
                }
            }
            if (!$businessData) {
                return responseJson(Base::FAIL,'数据获取失败');
            }
            $startTime = date('Y-m-01');
            $endTime = date('Y-m-d',strtotime("$startTime +1 month -1 day"));
            //使用商家id计算月销
            foreach ($businessData as $key => $value){
                $OnThePin = $order->countOrder($businessData[$key]['id'],$startTime,$endTime);
                $businessData[$key]['OnThePin'] = $OnThePin;
            }
            return responseJson(Base::OK,'数据获取成功',$businessData);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @hotPin  商家页-热销
     * @param Request $request
     * @param Commodity $commodity
     * @param OrderCommodity $orderCommodity
     * @return \think\response\Json
     */
    public function hotPin(Request $request,Commodity $commodity,OrderCommodity $orderCommodity,Order $order){
        try {
            $commodityAll = $commodity->commodityAll($request->post('businessId'),'id,businessId,commodityName,commodityImg,presentPrice,originalPrice');
            if ($commodityAll->isEmpty()){
                return responseJson(Base::OK,'暂无商品');
            }
            $commodityAll = json_decode($commodityAll,true);
            $startTime = date('Y-m-01');
            $endTime = date('Y-m-d',strtotime("$startTime +1 month -1 day"));
            //获取当前月份的订单
            $monthOrder = $order->monthOrder($request->post('businessId'),$startTime,$endTime);
            if ($monthOrder->isEmpty()){
                return responseJson(Base::OK,'暂无销售的商品');
            }
            //月销
            foreach ($commodityAll as $k => $val){
                $commodityAll[$k]['OnThePin'] = 0;
            }
            foreach ($monthOrder as $key => $value){
                if (empty($monthOrder)){
                    break;
                }
                $commodityId = $orderCommodity->findCommodity($monthOrder[$key]['orderNum']);
                foreach ($commodityAll as $k => $val){
                    if ($commodityAll[$k]['id'] != $commodityId[0]['cid']){
                        continue;
                    }
                    $commodityAll[$k]['OnThePin'] += 1;
                }
            }
            //判断月销
            $onThePin = [];
            foreach ($commodityAll as $k => $value){
                if ($commodityAll[$k]['OnThePin'] >= 10){
                    array_push($onThePin,$commodityAll[$k]);
                }
            }
            return responseJson(Base::OK,'数据获取成功',$onThePin);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @discount    商家页-折扣
     * @param Request $request
     * @param Commodity $commodity
     * @param OrderCommodity $orderCommodity
     * @return \think\response\Json
     */
    public function discount(Request $request,Commodity $commodity,OrderCommodity $orderCommodity,Order $order){
        try {
            $commodityAll = $commodity->commodityAll($request->post('businessId'),'id,businessId,commodityName,commodityImg,presentPrice,originalPrice');
            if ($commodityAll->isEmpty()){
                return responseJson(Base::OK,'暂无商品');
            }
            $commodityAll = json_decode($commodityAll,true);
            $startTime = date('Y-m-01');
            $endTime = date('Y-m-d',strtotime("$startTime +1 month -1 day"));
            //获取当前月份的订单
            $monthOrder = $order->monthOrder($request->post('businessId'),$startTime,$endTime);
            if ($monthOrder->isEmpty()){
                return responseJson(Base::OK,'暂无销售的商品');
            }
            $discount = [];

            //月销
            foreach ($commodityAll as $k => $val){
                $commodityAll[$k]['OnThePin'] = 0;
            }
            foreach ($monthOrder as $key => $value){
                if (empty($monthOrder)){
                    break;
                }
                $commodityId = $orderCommodity->findCommodity($monthOrder[$key]['orderNum']);
                foreach ($commodityAll as $k => $val){
                    if ($commodityAll[$k]['id'] != $commodityId[0]['cid']){
                        continue;
                    }
                    $commodityAll[$k]['OnThePin'] += 1;
                }
            }
            //判断数量
            foreach ($commodityAll as $k => $val){
                if ($commodityAll[$k]['presentPrice'] < $commodityAll[$k]['originalPrice']){
                    array_push($discount,$commodityAll[$k]);
                }
            }
            return responseJson(Base::OK,'数据获取成功',$discount);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @commodityClassification 商品分类
     * @param Request $request
     * @param CommodityClass $commodityClass
     * @param Commodity $commodity
     * @param OrderCommodity $orderCommodity
     * @return \think\response\Json
     */
    public function commodityClassification(Request $request,Order $order,CommodityClass $commodityClass,Commodity $commodity,OrderCommodity $orderCommodity){
        try {
            $commodityAll = $commodity->commodityAll($request->post('businessId'),'id,businessId,catId,commodityName,commodityImg,presentPrice,originalPrice');

            if ($commodityAll->isEmpty()){
                return responseJson(Base::OK,'暂无商品');
            }
            $commodityAll = json_decode($commodityAll,true);
            $startTime = date('Y-m-01');
            $endTime = date('Y-m-d',strtotime("$startTime +1 month -1 day"));
            //获取当前月份的订单
            $monthOrder = $order->monthOrder($request->post('businessId'),$startTime,$endTime);
            if ($monthOrder->isEmpty()){
                $monthOrder = [];
            }

            //月销
            foreach ($commodityAll as $k => $v){
                $commodityAll[$k]['OnThePin'] = 0;
            }
            foreach ($monthOrder as $key => $val){
                if (empty($monthOrder)){
                    break;
                }
                $commodityId = $orderCommodity->findCommodity($monthOrder[$key]['orderNum']);
                foreach ($commodityAll as $k => $v){
                    if ($commodityAll[$k]['id'] != $commodityId[0]['cid']){
                        continue;
                    }
                    $commodityAll[$k]['OnThePin'] += 1;
                }
            }
            //判断分类上架
            if (!$commodityClassData = json_decode($commodityClass->classificationName($request->post('businessId')),true)) {
                return responseJson(Base::FAIL,'暂无商品');
            }
            foreach ($commodityClassData as $key => $value){
                $commodityClassData[$key]['commodity'] = [];
                foreach ($commodityAll as $k => $v){
                    if ($commodityClassData[$key]['id'] == $commodityAll[$k]['catId']){
                        array_push($commodityClassData[$key]['commodity'],$commodityAll[$k]);
                    }
                }
            }
            return responseJson(Base::OK,'数据获取成功',$commodityClassData);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @showCarts   显示商家页商品的订单
     * @param Request $request
     * @param Carts $carts
     * @return \think\response\Json
     */
    public function showCarts(Request $request,Carts $carts,Commodity $commodity){
        try {
            $arr = json_decode(app('mycache')->get($_SERVER['HTTP_TOKEN']),true);
            $businessId = $request->post('businessId');
            $data = $carts->showBusinessPageCarts($arr['id'],$businessId);
            if ($data->isEmpty()) {
                return responseJson(Base::OK,'没有购物车数据',0);
            }
            foreach ($data as $key => $val){
                if (!$catData = $commodity->showCatData($data[$key]['commodityId'])){
                    return responseJson(Base::FAIL,'数据获取失败，请重试');
                }
                $data[$key]['commodityName'] = $catData['commodityName'];
                $data[$key]['presentPrice'] = $catData['presentPrice'];
                $data[$key]['commodityImg'] = $catData['commodityImg'];
            }
            return responseJson(Base::OK,'数据获取成功',$data);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @shoppingCart    商家页购物车
     * @param Request $request
     * @param Business $business
     * @param Carts $carts
     * @return \think\response\Json
     * @throws Exception
     */
    public function shoppingCart(Request $request,Business $business,Carts $carts){
        try {
            $arr = $request->cacheInfo;
            $commodityId = (int)$request->post('commodityId');
            $commodityNum = $request->post('commodityNumber');
            $businessId = $request->post('businessId');
            $businessName = $business->findBusiness($businessId);
            $userId = $arr['id'];
            if (!empty($cNum = json_decode($carts->findCart($userId,$commodityId,$businessName,$businessId),true))){
                if ($cNum['commondityNum'] == $commodityNum){
                    return responseJson(Base::OK,'数据更新成功');
                }
                if (!$carts->updateCart($userId,$commodityId,$businessName,$commodityNum)){
                    return responseJson(Base::FAIL,'数据更新失败，请重试');
                }
                return responseJson(Base::OK,'数据更新成功');
            }
            if (!$carts->cartInsert($userId,$businessId,$commodityId,$businessName,$commodityNum)){
                return responseJson(Base::FAIL,'数据刷新失败，请重试');
            }
            return responseJson(Base::OK,'数据插入成功');
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @emptyCarts  商家页清空购物车
     * @param Request $request
     * @param Business $business
     * @param Carts $carts
     * @return \think\response\Json
     */
    public function emptyCarts(Request $request,Business $business,Carts $carts){
        try {
            $arr = $request->cacheInfo;;
            $businessId = $request->post('businessId');
            $businessName = $business->findBusiness($businessId);
            if (!$data = $carts->delBusinessPageCats($arr['id'],$businessName)) {
                return responseJson(Base::FAIL,'数据删除失败');
            }
            return responseJson(Base::OK,'数据删除成功',$data);
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @singleDelete    商家页购物车单个删除
     * @param Request $request
     * @param Business $business
     * @param Carts $carts
     * @return \think\response\Json
     */
    public function singleDelete(Request $request,Business $business,Carts $carts){
        try {
            $arr = $request->cacheInfo;
            $commodityId = $request->post('commodityId');
            $businessId = $request->post('businessId');
            $businessName = $business->findBusiness($businessId);
            if (!$data = $carts->delSingleDelete($arr['id'],$businessId,$commodityId,$businessName)){
                return responseJson(Base::FAIL,'数据删除失败');
            }
            return responseJson(Base::OK,'数据删除成功',$data);
        }catch (Exception $e) {
            throw $e;
        }
    }
    /**
     * @historyBusiness     商家页历史商家
     * @param Request $request
     * @param History $history
     * @return \think\response\Json
     */
    public function historyBusiness(Request $request,History $history){
        try {
            $arr = $request->cacheInfo;
            $businessId = $request->post('businessId');
            if (!empty($history->findHistory($arr['id'],$businessId))){
                if (!$history->updateTime($arr['id'],$businessId)) {
                    return responseJson(Base::OK,'系统错误，请重试');
                }
                return responseJson(Base::OK,'数据修改成功');
            }
            if ($history->createHistory($arr['id'],$businessId)) {
                return responseJson(Base::OK,'系统错误，请重试');
            }
            return responseJson(Base::OK,'数据创建成功');
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @favoritesBusinessShow   商家页收藏店铺显示
     * @param Request $request
     * @param Favorites $favorites
     * @return \think\response\Json
     * @throws Exception
     */
    public function favoritesBusinessShow(Request $request,Favorites $favorites){
        try {
            $arr = $request->cacheInfo;
            $businessId = $request->post('businessId');
            if (empty($favorites->showFavorites($arr['id'],$businessId))){
                return responseJson(Base::OK,'0');
            }
            return responseJson(Base::OK,'1');
        }catch (Exception $e){
            throw $e;
        }
    }

    /**
     * @favoritesBusiness   商家页收藏商家
     * @param Request $request
     * @param Favorites $favorites
     * @return \think\response\Json
     */
    public function favoritesBusiness(Request $request,Favorites $favorites){
        try {
            $arr = $request->cacheInfo;
            $businessId = $request->post('businessId');
            if (!empty($favorites->findFavorites($arr['id'],$businessId))){
                if (!$favorites->delFavorites($arr['id'],$businessId)) {
                    return responseJson(Base::OK,'系统错误，请重试');
                }
                return responseJson(Base::OK,'取消收藏',0);
            }
            if (!$favorites->insertFavorites($arr['id'],$businessId)) {
                return responseJson(Base::OK,'系统错误，请重试');
            }
            return responseJson(Base::OK,'收藏成功',1);
        }catch (Exception $e){
            throw $e;
        }
    }
}